<template>
  <t-dialog
      header="新增测试用例"
      :visible.sync="showDialogAdd"
      @confirm="onConfirm"
      :confirmOnEnter="true"
      :onConfirm="onConfirmAnother"
      :onCancel="onCancel"
      :onEscKeydown="onKeydownEsc"
      :onCloseBtnClick="onClickCloseBtn"
      :onOverlayClick="onClickOverlay"
      :onClose="close"
      width='50%'
    >
    <t-space size="32px">
    <t-form
      :data="formData"
      labelWidth="calc(2em + 50px)"
      :layout="layout"
      ref="form"
      @reset="onReset"
      @submit="onSubmit"
      scrollToFirstError="smooth"
    >
      <t-form-item label="所属模块" name="module">
        <t-select
          v-model="formData.module"
          :style="{ width: '222px' }"
          class="demo-select-base"
          placeholder="请选择类型"
          clearable
        >
          <t-option v-for="(item, index) in MODULES_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
      <t-form-item label="迭代版本" name="testcase_version" layout="inline">
        <t-select
          v-model="formData.testcase_version"
          :style="{ width: '222px' }"
          placeholder="请选择"
          class="demo-select-base"
          :options="testCaseVersion"
          :keys="{ label: 'sprint_name', value: 'sprint_id' }"
          clearable
        >
          <!-- <t-option v-for="(item, index) in TESTCASE_VERSION_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option> -->
        </t-select>
      </t-form-item>
      <t-form-item>
            <t-form-item label="优先级" name="priority">
            <t-space size="10px">
              <t-check-tag theme="primary" size="large" :plain="item.checked == true ? false : true"
                v-for="(item , index) in priorityCheck" :key="index" @click="clickPriority(item)" v-model="item.checked">{{item.label}}
              </t-check-tag>
              <!-- <t-check-tag
                theme="primary" 
                size="large"                
                v-for="(item , index) in priorityCheck" 
                  :key="index"
                  :plain="item.checked"
                  @onclick="clickPriority"
                  @change="changePriority"
                >
                {{item.label}}               
              </t-check-tag> -->
            </t-space>  
            </t-form-item>

          </t-form-item>
            <!-- 标签 -->
            <t-form-item label="标签" name="tags">
                <t-select
                  v-model="formData.testcase_tags"
                  class="form-item-content"
                  placeholder="请选择标签"
                  :options="testCaseTags"
                  :keys="{ label: 'tag_name', value: 'tag_id' }"
                  multiple
                  :minCollapsedNum="3"
                  @change="handleChangeTags"
                  id="tags"
                  :style="{ minWidth: '134px' }"
                />               
              </t-form-item>
              <!-- 支持自定义标签，后面可能会用到 -->
            <!-- <template>
                <t-form-item label="标签" name="testcase_tags">
                  <t-space style="width: 150%">
                    <t-tag-input v-model="tags" 
                    :min-collapsed-num="3"
                    :autoWidth="true"
                    placeholder="请输入标签                                                  "
                    status="success"
                    >
                      <template #collapsedItems="{ collapsedTags }">
                        <t-popup>
                          <t-tag>More({{ collapsedTags.length }})</t-tag>
                          <template #content>
                            <t-tag v-for="item in collapsedTags" :key="item" style="margin-right: 40px">
                            {{ item }}
                            </t-tag>
                          </template>
                        </t-popup>
                      </template>
                    </t-tag-input>
                  </t-space>
                </t-form-item>
            </template> -->

        <t-form-item v-for="(item, index) in this.newData" :key="index" label="测试用例" :name="item.testcase_name" style="margin-top: 20px;">
        <t-input v-model="item.testcase_name" placeholder="请输入测试名称" style="margin-right: 10px;"></t-input>
        <t-input v-model="item.git_addr"  placeholder="请输入测试用例地址" ></t-input>
        <t-button
          v-if="index === 0 || index === lastAddTestCase - 1"
          @click="addTestCase"
          slot="statusIcon"
          variant="dashed"
        >
          <icon name="add" />
        </t-button>
        <t-button v-if="index> 0" @click="removeTestCase(item, index)" slot="statusIcon" variant="dashed">
          <icon name="remove" />
        </t-button>
      </t-form-item>
      <t-form-item :statusIcon="false" style="margin-left: 80px"></t-form-item>
    </t-form>
  </t-space>
  </t-dialog>
</template>

<script lang="jsx">
import { prefix } from '@/config/global';
import { Icon } from 'tdesign-icons-vue';
import { Tag } from 'tdesign-vue';


import {
  MODULES_OPTIONS,
  TESTCASE_PRIORITY_OPTIONS,
} from '@/constants';
import { operateTestCase} from '@/api/requestApi'
// import { CheckCircleFilledIcon, ErrorCircleFilledIcon, CloseCircleFilledIcon, Icon } from 'tdesign-icons-vue';

const INITIAL_FORM_DATA = [{
  testcase_name: '',
  testcase_tags: [],
  testcase_version: '',
  module: undefined,
  priority: undefined,
  git_addr: '',
}];
const FORM_RULES = {
  testcase_name: [{ required: true, message: '请输入用例名称', type: 'error' }],
  testcase_version: [{ required: true, message: '请选择版本', type: 'error' }],
  module: [{ required: true, message: '请选择所属模块', type: 'error' }],
  priority: [{ required: true, message: '请选择优先级', type: 'error' }],
  git_addr: [{ required: true, message: '请输入用例地址', type: 'error' }],
};

export default {
  name: 'AddDialogComp',
  components: {
    Icon,
    // MODULES_OPTIONS,
    // TESTCASE_VERSION_OPTIONS,
  },
  props: {
    showChildDialogAdd: {
      type: Boolean,
      default: false
    },
    testCaseTags: Array,
    testCaseVersion: Array,
  },
  data() {
    return {
      MODULES_OPTIONS,
      priorityCheckArr: [],
      priorityCheck: TESTCASE_PRIORITY_OPTIONS,
      layout: 'vertical', // 纵向布局
      lastAddTestCase: 1,
      newData: [{}],
      newFormDate: {...INITIAL_FORM_DATA[0]},
      formData: {...INITIAL_FORM_DATA[0]},
      FORM_RULES: {...FORM_RULES},
      tags: [],
      // renderCollapsedItems 支持自定义标签
      // renderCollapsedItems: (_, { collapsedTags }) => <Tag>更多({collapsedTags.length})</Tag>,
    };
  },
  
  computed: {
    showDialogAdd: {
      get() {
        return this.showChildDialogAdd
      },
      set(newValue) {
        this.$emit('update:showChildDialogAdd', newValue) // 触发更新事件，父组件的showDialogAdd会自动更新
      }
    },
  },
  mounted() {
    // this.$refs.formValidatorStatus.validate();
    this.priorityCheck.forEach(elment =>{
      elment.checked = false;
    })
  },
  methods: {
    init(data) {
      // this.showDialog=true;
      // data是父组件弹窗传递过来的值，我们可以打印看看
      this.formData = data
      console.log('来自父组件的', data);
    },
    clickPriority(item){
      this.priorityCheckArr.splice(0, 1)
      this.priorityCheckArr.push(item.value)
      this.formData.priority =item.value
    },
    changePriority(){
      console.log('changePriority')
    },
    onConfirm() {
      this.dataLoading = true;
      const selectTags = this.formData.testcase_tags.map((tag) => {
        const item = this.testCaseTags.find((obj) => obj.tag_id === tag);
        return item ? item.tag_name : null;
      })
      this.newData.forEach(item => {
        item.module = this.formData.module;
        console.log('module',this.formData.module,'version',this.formData.testcase_version)
        item.testcase_version = this.formData.testcase_version;
        item.testcase_tags = selectTags;
        item.priority = this.formData.priority;
      });
      console.log("提交的表单内容", this.newData);
      this.$request
        .post(operateTestCase(),{"ids":[],"op_type": "1","param": this.newData})
        .then((res) => {
          if (res.data.code === '000') {
            this.$message.success('测试用例创建成功');
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.formData.priority = '';
      this.showDialogAdd = false;
      
    },
    onConfirmAnother() {
      console.log('点击了确认按钮');
      // this.$emit('addFlush')
    },
    close() {
      // this.$emit('addOrUpdateVisible', false)
      // console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发');
    },
    onCancel() {
      this.showDialogAdd = false;
      // console.log('点击了取消按钮');
    },
    onKeydownEsc() {
      // console.log('按下了ESC');
    },
    onClickCloseBtn() {
      // console.log('点击了关闭按钮');
    },
    onClickOverlay() {
      // console.log('点击了蒙层');
    },
    onReset(data) {
      // console.log(data);
    },
    onSubmit(data) {
      // console.log(data);
    },
    addTestCase() {
      this.formData.testcase_name = '';
      this.formData.git_addr = '';
      // this.newData.push(this.newFormDate)
      this.newData.push({testcase_name:'', git_addr: ''})
    },
    removeTestCase(item, index) {
      // delete INITIAL_FORM_DATA[`add${item.id}`];
      this.newData.splice(index, 1);
    },
    handleChangeTags(...args) {
      // console.log('change', ...args);
    },
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

/deep/ [class*='t-table-expandable-icon-cell'] .t-icon {
  background-color: transparent;
}


.t-button + .t-button {
  margin-left: var(--td-comp-margin-s);
}
.t-button {
  margin-right: 20px;
}
.tdesign-demo-form-status .t-input {
  width: 520px;
}
.tdesign-demo__panel-options-multiple {
  width: 100%;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.tdesign-demo__panel-options-multiple .t-checkbox {
  display: flex;
  border-radius: 3px;
  line-height: 22px;
  cursor: pointer;
  padding: 3px 8px;
  color: var(--td-text-color-primary);
  transition: background-color 0.2s linear;
  white-space: nowrap;
  word-wrap: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0;
}
.tdesign-demo__panel-options-multiple .t-checkbox:hover {
  background-color: var(--td-bg-color-container-hover);
}

</style>
